package net.ryian.sms.service.impl;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;

import java.net.URLEncoder;


/**
 * Created by allenwc on 2016/11/10.
 */
public class TzSmsService extends BaseSmsService {

    private String ip;
    private String no;
    private String username;
    private String pwd;

    public TzSmsService() {
        ip = prop.getProperty("tzsms.ip");
        no = prop.getProperty("tzsms.no");
        username = prop.getProperty("tzsms.username");
        pwd = prop.getProperty("tzsms.pwd");
    }

    @Override
    public void send(String mobile, String msg) throws Exception {
        String URL = "http://{ip}/mas_https/send.jsp?usr={username}&srcid={no}&mobile={mobile}&msg={msg}&yzm={yzm}&tjpc=1";
        String yzm = String.valueOf(Integer.parseInt(mobile.substring(7))*3+Integer.parseInt(pwd));
        URL = URL.replace("{ip}",ip).replace("{username}",username).replace("{no}",no).replace("{mobile}",mobile).replace("{msg}", URLEncoder.encode(msg,"GBK")).replace("{yzm}",yzm);
        HttpClient client = new HttpClient();
        GetMethod get = new GetMethod(URL);
//        get.addRequestHeader("Content-Type",
//                "application/x-www-form-urlencoded;charset=UTF-8");// 在头文件中设置转码
        client.executeMethod(get);
        String result = new String(get.getResponseBodyAsString().getBytes(
                "GBK"));
        get.releaseConnection();

        String result_code = null;
        if (result != null) {
            result_code = result.replaceAll("\\r","").replaceAll("\\n","").replaceAll("\\t","").replaceAll(" ","");
        }
        if (!result_code.startsWith("0")) {
            throw getSendExeption(result);
        }
    }

    @Override
    public void send(String mobile, String template, String... values) throws Exception {

    }

    private Exception getSendExeption(String result) {
        String ex = null;
        if ("-4".equals(result)) {
            ex = "系统错误";
        } else if ("-1".equals(result)) {
            ex = "用户名或密码错";
        } else if ("-7".equals(result)) {
            ex = "验证码错误";
        } else if ("-13".equals(result)) {
            ex = "定时发送时间格式不对";
        } else if ("-3".equals(result)) {
            ex = "定时发送时间格式不对";
        } else if ("-6".equals(result)) {
            ex = "超出单次最大提交数";
        } else if ("-11".equals(result)) {
            ex = "消息内容不能超过300字";
        } else if ("-10".equals(result)) {
            ex = "消息内容不能为空";
        } else if ("-2".equals(result)) {
            ex = "提交失败";
        } else if ("-12".equals(result)) {
            ex = "短信提交批次不能为空";
        } else {
            ex = "未知错误，result:" + result;
        }
        return new Exception(ex);
    }

	@Override
	public void send(String mobile, String templatecode, String signature, String... values) throws Exception {
		// TODO Auto-generated method stub
		
	}

}
